package com.fz.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by webrx on 2017-09-05.
 */
@WebServlet("/down.action")
public class Download extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //String fileName = "smvc02.rar";
        String fileName = req.getParameter("name");
        String downname = new SimpleDateFormat("yyyyMMddhhmmssS").format(new Date())+fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        String path = req.getServletContext().getRealPath("/download/");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("multipart/form-data");
        resp.setHeader("Content-Disposition", "attachment;fileName=" + downname);
        InputStream is = new FileInputStream(path+fileName);
        OutputStream os = resp.getOutputStream();
        byte[] buf = new byte[10240];
        int i = 0;
        while((i = is.read(buf)) > 0)    {
            os.write(buf, 0, i);
        }
        os.flush();
        os.close();
        is.close();
    }
}
